<!--添加产品组件-->
<template>
  <div>
    <el-dialog
      :title="title"
      :visible="dialogVisible"
      @close="cancelDialog"
      width="1200px"
      class="edit-form">
      <!-- 搜索模块 -->
      <SearchForm
        show-collapse
        :data="productListSearchForm"
        :compact-data="compactProductListSearchForm"
        label-width="120px"
        @remoteMethod="remoteMethod"
        @searchForm="searchForm"
        @resetForm="resetForm"
        ref="search"
      />
      <!-- 列表模块 -->
      <el-editable
        ref="productTable"
        class="hospital-edit-box"
        v-loading="productLoading"
        :data="productList"
        height="400"
        :columns="productListColumns"
        @selection-change="handleSelectionChange"
      >
        <template
          slot="default-unit"
          slot-scope="{row}">
          <el-select
            v-model="row.unit"
            clearable
            style="width:100px;"
            placeholder="请选择">
            <el-option
              v-for="item in unitOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </template>
        <template
          slot="default-purchaseNum"
          slot-scope="scope">
          <el-input-number
            v-model="scope.row.purchaseNum"
            @change="resetIllegalInput(scope.row,$event)"
            size="mini"
            :min="1"
            :max="10e6" />
        </template>
      </el-editable>
      <!-- 分页模块 -->
      <el-pagination
        align="right"
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      />
      <div
        slot="footer"
        class="dialog-footer">
        <el-button @click="cancelDialog">取消</el-button>
        <el-button
          type="primary"
          @click="confirmDialog">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import SearchForm from '@components/businesscomponents/search'
import ElEditable from '@components/el-editable'

import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import { authItemCommonNameQuery } from '@const/beforeSettleApi'
import { UNIT_OPTIONS, productListColumns, productListSearchForm } from './const'
export default {
  name: 'AddProductDialog',
  components: {
    SearchForm, ElEditable
  },
  props: {
    title: {
      type: String,
      default: '添加产品'
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    queryUrl: { // 产品列表查询url
      type: String,
      default: '#'
    },
    queryMethod: {
      type: String,
      default: 'get'
    },
    extraQuery: { // 要添加的额外请求参数
      type: Object,
      default: () => {}
    },
    currentProducts: { // 已经添加到页面中的产品，用于处理接口以加数据中的选中状态
      type: Array,
      default: () => []
    },
    productListColumns: {
      type: Array,
      default: () => productListColumns
    },
    productListSearchForm: {
      type: Array,
      default: () => productListSearchForm
    }
  },
  data () {
    return {
      unitOptions: UNIT_OPTIONS,
      curPage: 1,
      PAGE_NUMBER,
      PAGINATION_LAYOUT,
      pageSize: PAGE_NUMBER[0],
      totalElements: 0,
      productList: [], // 添加产品弹窗中，根据筛选条件查询出的可以添加的产品列表
      searchQuery: {},
      productLoading: false,
      productSelectedList: [],
      allSelectedList: [], // 全部选中的项，初始值总是为创建订单页面中已经有的项
      addedList: this.currentProducts // 已经添加到外部页面中的产品列表
    }
  },
  computed: {
    compactProductListSearchForm () {
      return this.productListSearchForm.slice(0, 2)
    }
  },
  watch: {
    dialogVisible (visible) {
      if (visible) {
        this.getProductList()
      }
    },
    currentProducts (val) {
      this.addedList = val
    }
  },
  methods: {
    getProductList () {
      const postData = {
        ...this.extraQuery,
        ...this.searchQuery,
        page: this.curPage,
        pageSize: this.pageSize
      }
      const url = this.queryUrl
      const method = '$' + this.queryMethod
      this.productLoading = true
      this.$axios[method](url, postData)
        .then(res => {
          this.productList = res.payload.content
          this.totalElements = res.payload.totalElements
          this.setCurrentSelection()
        })
        .finally(() => {
          this.productLoading = false
        })
    },
    resetIllegalInput (row, value) {
      if (value % 1 !== 0) {
        row.purchaseNum = Math.round(value)
      }
    },
    remoteMethod (value, key) {
      // if (key === 'idList') {
      //   this.getAuthItemName(value)
      // }
    },
    // getAuthItemName (value) {
    //   const postData = {
    //     ...this.extraQuery,
    //     name: value,
    //     pageSize: 10e6
    //   }
    //   const item = this.productListSearchForm.find(item => item.key === 'idList')
    //   this.$set(item.attr, 'loading', true)
    //   this.$axios.$post(authItemCommonNameQuery, postData)
    //     .then(res => {
    //       const nameList = res.payload.content
    //       const options = nameList.map(item => {
    //         return {
    //           label: item.value,
    //           value: [item.id]
    //         }
    //       })
    //       this.$set(item, 'options', options)
    //     })
    //     .catch(e => {})
    //     .finally(() => {
    //       this.$set(item.attr, 'loading', false)
    //     })
    // },
    searchForm (condition) {
      this.curPage = 1
      this.searchQuery = condition
      this.getProductList()
    },
    resetForm (condition) {
      this.curPage = 1
      this.searchQuery = condition
      this.getProductList()
    },
    confirmDialog () {
      this.updateAllSelectedList()
      if (!this.allSelectedList.length) {
        this.$message.warning('请选择产品')
        return
      }
      this.$emit('confirmDialog', this.allSelectedList)
      this.productList = []
      this.allSelectedList = []
    },
    cancelDialog () {
      this.productList = []
      this.allSelectedList = []
      this.$emit('cancelDialog')
      this.$refs.search.reset()
    },
    handleSizeChange (size) {
      this.pageSize = size
      this.getProductList()
      this.updateAllSelectedList() // 换页就更新全部选中项数组
    },
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.getProductList()
      this.updateAllSelectedList() // 改变页大小也更新全部选中项数组
    },
    handleSelectionChange (selection) {
      selection.map(item => {
        if (!item.purchaseNum) item.purchaseNum = 1
      })
      this.productSelectedList = selection
    },
    updateAllSelectedList () { // 更新allSelectedList数组，在换页和改变每页大小的时候执行
      this.productSelectedList.forEach(item => {
        const findItem = this.allSelectedList.find(selected => selected.id === item.id)
        if (!findItem) { // 没有就添加
          this.allSelectedList.push(item)
        } else { // 有就更新数量
          findItem.purchaseNum = item.purchaseNum
        }
      })
    },
    setCurrentSelection () { // 如果当前项已经在外部页面中了或者已经被选中过就选中
      this.addedList.forEach(item => {
        const findItem = this.productList.find(product => product.id === item.authProdId)
        // if (findItem) {
        //   this.$nextTick(() => {
        //     findItem.purchaseNum = item.purchaseNum
        //     this.$refs.productTable.$refs.table.toggleRowSelection(findItem, true)
        //   })
        // }
      })
      this.allSelectedList.forEach(selected => {
        const findItem = this.productList.find(product => selected.id === product.id)
        // if (findItem) {
        //   this.$nextTick(() => {
        //     findItem.purchaseNum = selected.purchaseNum
        //     this.$refs.productTable.$refs.table.toggleRowSelection(findItem, true)
        //   })
        // }
      })
    }
  }

}
</script>
<style lang="less">

</style>
